package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.BargainRecordAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.car.BargainRecord;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 砍价记录
 * Created by chuang on 2016/8/3.
 */
public class BargainRecordActivity extends BaseActivity implements NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {

    private PullToRefreshListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ListView listView;

    private View footView;

    private List<BargainRecord> mBargainRecord;

    private NetDataJson mNetDataJson;

    private BargainRecordAdapter mBargainRecordAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private NetDataJson addResultNetDataJson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "my_bargainRecord";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse_layout);
        setTitle("砍价记录");
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);

        mBargainRecord = new ArrayList<>();
        mBargainRecordAdapter = new BargainRecordAdapter(mBargainRecord, this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mBargainRecordAdapter);
        listView.setOnItemClickListener(this);
        listView.removeFooterView(footView);
        listView.setClipToPadding(false);

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.setUrl(API.bargainHistory);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        Intent intent = new Intent();
        BargainRecord br = mBargainRecord.get(position - 1);
        if (br != null) {
            intent.setClass(this, CarBuyDetailActivity.class);
            intent.putExtra("typevalue", String.valueOf(br.car_id));
            /*intent.putExtra("type", "fromHistory");
            intent.putExtra("from", "favorite");*/
            startActivity(intent);
        }
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (addResultNetDataJson != null) {
            addResultNetDataJson.cancelTask();
            addResultNetDataJson = null;
        }

    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mBargainRecord.clear();
            mBargainRecordAdapter.setData(mBargainRecord);
        }
        try {
            JSONObject jsonObject = json.getJSONObject("data");
            jsonArray = jsonObject.getJSONArray("bargains");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }

            for (int i = 0; i < jsonArray.length(); i++) {
                BargainRecord br = new BargainRecord();
                JSONObject object = jsonArray.getJSONObject(i);
                br.status = object.getString("status");
                br.mile = object.getString("mile");
                br.price = object.getString("price");
                br.month = object.getString("month");
                br.title = object.getString("title");
                br.eval_price = object.getString("eval_price");
                br.year = object.getString("year");
                br.id = object.getInt("id");
                br.pub_time = object.getString("pub_time");
                br.expected_price = object.getString("expected_price");
                br.thumbnail = object.getString("thumbnail");
                br.car_id = object.getInt("car_id");
                br.car_status = object.getString("car_status");
                mBargainRecord.add(br);
            }
            int page_num = jsonObject.getInt("page_num");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(this, "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        mBargainRecordAdapter.setData(mBargainRecord);
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

}
